package SyncMap

import (
	"net"
	"sync"
)

type TCPConn struct {
	lock *sync.RWMutex
	data map[string]*net.TCPConn
}

func NewTCPConn() *TCPConn {
	return &TCPConn{
		lock: new(sync.RWMutex),
		data: make(map[string]*net.TCPConn),
	}
}

//Get from maps return the k's value
func (m *TCPConn) Get(k string) (val *net.TCPConn, ok bool) {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if val, ok = m.data[k]; ok {
		return
	}
	ok = false
	return
}

// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *TCPConn) Set(k string, v *net.TCPConn) bool {
	m.lock.Lock()
	defer m.lock.Unlock()
	if val, ok := m.data[k]; !ok {
		m.data[k] = v
	} else if val != v {
		m.data[k] = v
	} else {
		return false
	}
	return true
}

// Returns true if k is exist in the map.
func (m *TCPConn) Check(k string) bool {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if _, ok := m.data[k]; !ok {
		return false
	}
	return true
}

func (m *TCPConn) Delete(k string) {
	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.data, k)
}

func (m *TCPConn) Items() map[string]*net.TCPConn {
	m.lock.RLock()
	defer m.lock.RUnlock()
	return m.data
}
